// pages/login1/login.js
const mybehavior = require("../../behaviors/requests")

import JSEncrypt from 'jsencrypt-miniprogram'

Page({

    /**
     * 页面的初始数据
     */
    behaviors: [mybehavior],
    data: {
        base_urlstr: "https://logisticsengineering.gree.com/gm_user",
        login_style_yzm: "position: absolute;width: 160rpx;height: 32rpx;left: 48rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 600;",
        login_style_user: "position: absolute;width: 160rpx;height: 32rpx;left: 282rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 250;",
        login_style_flag: "position: absolute;width: 94rpx;height: 12rpx;left: 80rpx;top: 104rpx;background-color: #5555FF;border-radius: 6rpx 6rpx 6rpx 6rpx;",
        login_style_show: true,
        yam_word: "发送验证码",
        employee_num: "",
        email: "",
        password: "",
        phone_num: "",
        verification_code: "",
        count: 0,
        yzm_show: false,
        yam_btn_disabled: false,
        yam_btn: "primary",
        login_btn1: true,
        login_btn2: true,
        eye_show: "closed-eye",
        password_show: true,
        yzm_btn_style: "color: #aeaeff;",
        checked: false,
        show_privacy: false,
        privacy_name: "《格力智慧GMS小程序隐私协议》",
        code_focus: false,
        user_show: false,
        yzm_show: false,
        imageSrc: "",
        captcha: "",
    },
    RSAEncrypt(password) {

        const encryptor = new JSEncrypt();
        const publicKey = "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYHn26fpSbRH9pltQGN2eRVLQIakv0hugZFLWYlKb/W8sz4RCYwaqWfotPKGkBcUajLbo+YZKLQZjFEx/RNQ97AJNjaPeSPbS7DVIe4JQw1ysDWYwFewIazVKds4xSqgt7EYgfj3TVwTAVufpA2lehFfkGAYOWsPYOwHUYGNOkbQIDAQAB-----END PUBLIC KEY-----"
        encryptor.setPublicKey(publicKey);
        const encrypted = encryptor.encrypt(password); // 返回 base64 字符串
        if (encrypted) {
            return encrypted
        } else {
            return wx.showToast({
                title: '加密失败',
                icon: 'none'
            });
        }
    },
    noLogin() {
        wx.navigateTo({
            url: '/pages/home1/home1',
        })
    },

    onCorifm1() {
        this.setData({
            show_privacy: false
        })
    },
    onClose1() {
        this.setData({
            show_privacy: false
        })
    },
    toRgisterUser() {
        wx.navigateTo({
            url: '/pages/register_user/register_user',
        })
    },
    handleOpenPrivacyContract() {
        // 打开隐私协议页面
        wx.openPrivacyContract({
            success: () => { }, // 打开成功
            fail: () => { }, // 打开失败
            complete: () => { }
        })
    },

    onChange(event) {
        console.log(event);
        this.setData({
            checked: event.detail,
        });

    },
    // 邮箱号输入完成
    // focusCodeInput(e) {
    //   if (e.detail.length == 6) {
    //     this.setData({
    //       email_password_focus: true,

    //     })
    //   }
    // },
    onClose() {
        this.setData({
            yzm_show: false,
        })
    },
    showPassword() {
        if (this.data.eye_show == "eye-o") {
            this.setData({
                eye_show: "closed-eye",
                password_show: true

            })
        } else {
            this.setData({
                eye_show: "eye-o",
                password_show: false

            })
        }
    },
    checkLoginBtn(e) {
        console.log(e.currentTarget.dataset.data);
        let key = e.currentTarget.dataset.data
        if (this.data.phone_num != "") {
            this.setData({
                yzm_btn_style: "color: #5555FF;"

            })
        } else {
            this.setData({
                yzm_btn_style: "color: #aeaeff;"

            })
        }
        if (key == "login_btn1") {
            if (this.data.phone_num != "" && this.data.verification_code != "") {
                this.setData({
                    login_btn1: false,

                })
            } else {
                this.setData({
                    login_btn1: true,

                })
            }
        } else {
            if (this.data.email != "" && this.data.password != "") {
                this.setData({
                    login_btn2: false,

                })
            } else {
                this.setData({
                    login_btn2: true,

                })
            }
        }
    },
    // 验证码登录
    yzmLogin() {
        let style1 = "position: absolute;width: 160rpx;height: 32rpx;left: 48rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 600;"
        let style2 = "position: absolute;width: 160rpx;height: 32rpx;left: 282rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 250;"
        let style3 = "position: absolute;width: 94rpx;height: 12rpx;left: 80rpx;top: 104rpx;background-color: #5555FF;border-radius: 6rpx 6rpx 6rpx 6rpx;"
        this.setData({
            login_style_show: true,
            login_style_yzm: style1,
            login_style_user: style2,
            login_style_flag: style3,
        })
    },

    // 账号登录
    userLogin() {
        let style1 = "position: absolute;width: 160rpx;height: 32rpx;left: 48rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 250;"
        let style2 = "position: absolute;width: 160rpx;height: 32rpx;left: 282rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 600;"
        let style3 = "position: absolute;width: 94rpx;height: 12rpx;left: 298rpx;top: 104rpx;background-color: #5555FF;border-radius: 6rpx 6rpx 6rpx 6rpx;"
        this.setData({
            login_style_show: false,
            login_style_yzm: style1,
            login_style_user: style2,
            login_style_flag: style3,
        })
    },

    // 发送按钮倒计时
    sentBtn() {
        var a = this.data.count
        var t = this.data.yam_word
        if (a < 60) {
            this.setData({
                yam_word: t - 1,
                count: a + 1,
            })
            setTimeout(() => {
                this.sentBtn()
            }, 1000)
        } else {
            this.setData({
                yam_word: "发送验证码"
            })

        }

    },
    // 发送验证码
    sentCode() {



        var url = "https://logisticsengineering.gree.com/gm_user/gm_get_verification_code2";
        var data = {
            captcha: this.data.captcha,
            phone_num: this.data.phone_num,
        }
        console.log("发送验证码", data)
        this.post(url, data).then(res => {
            console.log("发送验证码返回信息", res)
            if (res.code == 20000) {
                this.setData({
                    yzm_show: false,
                    captcha: "",
                    yam_btn_disabled: true,
                    yam_word: 60,
                    count: 0,
                    code_focus: true
                })
                this.sentBtn()

                wx.showToast({
                    title: res.msg,
                    icon: "success"
                });
            } else {

                wx.showToast({
                    title: res.msg,
                    icon: "error"
                })
            }
        }).catch(err => {

            wx.showToast({
                title: err.msg,
                icon: 'error'
            })
        })


    },


    // 获取图形验证码
    BerforeSentCode() {
        if (this.data.checked == false) {
            wx.showToast({
                title: '请阅读并勾选同意《隐私协议》',
                icon: 'none'
            })

        } else {

            wx.showLoading({
                title: '加载中....',
            })
            var url = "https://logisticsengineering.gree.com/gm_user/gm_get_captcha";
            var data = {
                phone_num: this.data.phone_num,
            }
            let self = this

            wx.request({
                url: url,
                data: data,
                responseType: 'arraybuffer',
                success(res) {
                    if (res.statusCode == 200) {
                        const arrayBuffer = res.data;
                        // 将 ArrayBuffer 转为 Base64
                        const base64 = wx.arrayBufferToBase64(arrayBuffer);
                        // 直接用作图片源（需后台返回完整Base64带前缀）
                        self.setData({
                            imageSrc: 'data:image/png;base64,' + base64,
                            yzm_show: true,
                        });

                    } else {
                        wx.showToast({
                            title: '手机号有误，请重新确认！',
                            icon: 'none'
                        })
                    }

                    wx.hideLoading()

                }
            });

        }

    },

    onCloseLogin() {
        this.setData({
            yzm_show: false,
            captcha: ""
        })
    },
    onConfirmLogin() {
        if (this.data.captcha == "") {
            wx.showToast({
                title: '请输入图形验证码！',
                icon: 'none'
            })
        } else {

            this.sentCode()
        }
    },





    // 手机验证码登录111
    phoneLogin1() {
        if (this.data.checked == false) {
            wx.showToast({
                title: '请阅读并勾选同意《隐私协议》',
                icon: 'none'
            })

        } else {
            if (this.data.phone_num == "") {
                wx.showToast({
                    title: '手机号不能为空！',
                    icon: 'none'
                })
            } else if (this.data.verification_code == "") {
                wx.showToast({
                    title: '验证码不能为空！',
                    icon: 'none'
                })
            } else {

                wx.showLoading({
                    title: '登录中'
                })
                var url = this.data.base_urlstr + "/wx_login_in_by_verification_code";
                var data = {
                    phone_num: this.data.phone_num,
                    verification_code: this.data.verification_code,
                }
                console.log("手机验证码登录", data)
                this.post(url, data).then(res => {
                    setTimeout(function () {
                        wx.hideLoading()
                    }, 2000)
                    console.log("手机验证码登录返回信息", res)

                    if (res.code == 20000) {

                        wx.setStorageSync('company', res.data.company)
                        wx.setStorageSync('phone_num', res.data.phone_num)
                        wx.setStorageSync('email', res.data.short_email)
                        wx.setStorageSync('token', res.data.token)
                        wx.setStorageSync('name', res.data.name)
                        wx.setStorageSync('_id', res.data._id)
                        wx.setStorageSync('department', res.data.department);
                        wx.setStorageSync('ID_number', res.data.ID_number);
                        wx.setStorageSync('room', res.data.room);
                        wx.setStorageSync('category', res.data.category);
                        wx.redirectTo({
                            url: '/pages/home1/home1',
                        })
                        wx.showToast({
                            title: res.msg,
                            icon: "success"
                        });
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: "none"
                        })
                    }
                }).catch(err => {
                    console.log(err);
                    wx.hideLoading()
                    if (err.msg == "未注册!") {
                        this.setData({
                            user_show: true
                        })
                    } else {
                        wx.showToast({
                            title: err.msg,
                            icon: "none"
                        })
                    }



                })
            }

        }

    },
    onUserClose() {
        this.setData({
            user_show: false

        })
    },




    // 邮箱登录
    emailLogin() {
        let that = this;
        if (this.data.checked == false) {
            wx.showToast({
                title: '请阅读并勾选同意《隐私协议》',
                icon: 'none'
            })
        } else {
            if (this.data.user_email == "") {
                wx.showToast({
                    title: '帐号不能为空！',
                    icon: 'none'
                })
            } else if (this.data.password == "") {
                wx.showToast({
                    title: '密码不能为空！',
                    icon: 'none'
                })
            } else {

                wx.showLoading({
                    title: '登录中'
                })
                const basePassword = this.RSAEncrypt(this.data.password);

                var url = this.data.base_urlstr + "/wx_login3";
                var data = {
                    user_email: this.data.email,
                    password: basePassword
                }
                console.log("邮箱登录数据", data)
                this.post(url, data).then(res => {
                    // that.getOpenID()
                    setTimeout(function () {
                        wx.hideLoading()
                    }, 2000)
                    console.log("邮箱登录返回信息", res)
                    if (res.code == 20000) {

                        wx.setStorageSync('company', res.data.company)
                        wx.setStorageSync('phone_num', res.data.phone_num)
                        wx.setStorageSync('email', that.data.email)
                        wx.setStorageSync('token', res.data.token)
                        wx.setStorageSync('name', res.data.name)
                        wx.setStorageSync('_id', res.data._id)
                        wx.setStorageSync('department', res.data.department);
                        wx.setStorageSync('ID_number', res.data.ID_number);
                        wx.setStorageSync('room', res.data.room);
                        wx.setStorageSync('category', res.data.category);
                        wx.redirectTo({
                            url: '/pages/home1/home1',
                        })
                        wx.showToast({
                            title: res.msg,
                            icon: "success"
                        });
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: "error"
                        })
                    }
                }).catch(err => {
                    wx.showToast({
                        title: err.msg,
                        icon: 'error'
                    })
                })
            }

        }

    },
    getYzm(e) {
        console.log("验证码", e.detail.value);
        this.phoneLogin(e.detail.value)
    },
    // 手机验证码登录
    phoneLogin(e) {
        if (this.data.phone_num == "" || e == "") {
            wx.showToast({
                title: '不能为空',
                icon: 'error'
            })

        } else {
            wx.showLoading({
                title: '登录中'
            })
            var url = this.data.base_urlstr + "/wx_login_in_by_verification_code";
            var data = {
                phone_num: this.data.phone_num,
                verification_code: e,
            }
            console.log("手机验证码登录", data)
            this.post(url, data).then(res => {
                setTimeout(function () {
                    wx.hideLoading()
                }, 2000)
                console.log("手机验证码登录返回信息", res)

                if (res.code == 20000) {
                    this.setData({
                        yzm_show: false
                    })
                    wx.setStorageSync('company', res.data.company)
                    wx.setStorageSync('phone_num', res.data.phone_num)
                    wx.setStorageSync('email', that.data.email)
                    wx.setStorageSync('token', res.data.token)
                    wx.setStorageSync('name', res.data.name)
                    wx.setStorageSync('_id', res.data._id)
                    wx.setStorageSync('department', res.data.department);
                    wx.setStorageSync('ID_number', res.data.ID_number);
                    wx.setStorageSync('room', res.data.room);


                    wx.redirectTo({
                        url: '/pages/home1/home1',
                    })
                    wx.showToast({
                        title: res.msg,
                        icon: "success"
                    });
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: "none"
                    })
                }
            }).catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: 'none'
                })
            })
        }

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})